<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="灾害详情"> 灾害详细信息 </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard" size="small" :segmented="{ content: true }">
      <n-descriptions label-placement="left" class="py-2">
        <n-descriptions-item>
          <template #label>灾害ID</template>
          {{ disaster.disasterID }}
        </n-descriptions-item>
        <n-descriptions-item label="灾害类型">
          <n-tag type="info">{{ disaster.disasterType }}</n-tag>
        </n-descriptions-item>
        <n-descriptions-item label="上报用户ID">{{ disaster.userID }}</n-descriptions-item>
        <n-descriptions-item label="经度">{{ disaster.longitude }}</n-descriptions-item>
        <n-descriptions-item label="纬度">{{ disaster.latitude }}</n-descriptions-item>
        <n-descriptions-item label="位置信息">
          <span v-if="loading">正在获取位置...</span>
          <span v-else>{{ locationText }}</span>
        </n-descriptions-item>
        <n-descriptions-item label="状态">
          <n-tag :type="getStatusType(disaster.status)">{{ getStatusText(disaster.status) }}</n-tag>
        </n-descriptions-item>
        <n-descriptions-item v-if="disaster.video_url" label="图片URL">
          <n-ellipsis style="max-width: 300px">
            {{ disaster.video_url }}
          </n-ellipsis>
          <n-button text type="primary" size="small" class="ml-2" @click="copyImageUrl">
            复制
          </n-button>
        </n-descriptions-item>
      </n-descriptions>
      
      <n-divider />
      
      <div class="disaster-content">
        <h3>灾害描述</h3>
        <div class="content-box">{{ disaster.disasterInfo }}</div>
      </div>
      
      <n-divider />
      
      <!-- 灾害位置地图 -->
      <div class="disaster-map">
        <h3>灾害位置</h3>
        <div class="map-container">
          <el-amap 
            ref="mapRef" 
            :center="mapCenter" 
            :zoom="15" 
            :pitch="0" 
            :viewMode="'3D'" 
            :amap-options="amapOptions"
            class="amap-box"
          >
            <el-amap-marker 
              :position="mapCenter" 
              :label="{
                content: getDisasterLabel(),
                direction: 'bottom',
                offset: [0, -5]
              }"
            />
            <el-amap-control-scale />
            <el-amap-control-tool-bar />
            <el-amap-control-map-type :map-types="['satellite', 'standard']" />
          </el-amap>
        </div>
      </div>
      
      <n-divider />
      
      <!-- 灾害图片展示区域 -->
      <div v-if="disaster.video_url" class="disaster-image">
        <h3>灾害图片/视频</h3>
        <n-card hoverable class="image-card">
          <template #cover>
            <div class="image-container">
              <img :src="disaster.video_url" class="disaster-image-preview" />
            </div>
          </template>
        </n-card>
      </div>
      
      <n-divider />
      
      <div class="action-buttons" v-if="disaster.status !== 'resolved'">
        <n-space>
          <n-button 
            type="success" 
            @click="handleVerify" 
            v-if="disaster.status === 'unverified'"
          >
            验证灾害
          </n-button>
          <n-button 
            type="info" 
            @click="handleResolve" 
            v-if="disaster.status === 'verified'"
          >
            标记为已解决
          </n-button>
        </n-space>
      </div>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useMessage } from 'naive-ui';
import { RoadDisasterApi } from '@/api/RoadDisasterApi';
import MapUtils from '@/utils/Map/MapUtils';
import { ElAmap, ElAmapMarker, ElAmapControlScale, ElAmapControlToolBar, ElAmapControlMapType } from '@vuemap/vue-amap';

const route = useRoute();
const router = useRouter();
const message = useMessage();
const mapRef = ref(null);

const disaster = ref({
  disasterID: 0,
  disasterType: '',
  disasterInfo: '',
  longitude: 0,
  latitude: 0,
  userID: 0,
  status: 'unverified',
  video_url: '',
});

const locationText = ref('正在获取位置信息...');
const loading = ref(true);

// 地图配置
const mapCenter = computed(() => [disaster.value.longitude, disaster.value.latitude]);
const amapOptions = {
  resizeEnable: true,
  rotateEnable: true,
  pitchEnable: true,
  buildingAnimation: true,
};

// 状态映射
const statusMap = {
  unverified: '待验证',
  verified: '已验证',
  resolved: '已解决',
};

// 状态标签类型映射
const statusTypeMap = {
  unverified: 'warning',
  verified: 'info',
  resolved: 'success',
};

// 灾害类型映射
const disasterTypeMap = {
  '洪水': 'flood',
  '火灾': 'fire',
  '地震': 'earthquake',
  '塌方': 'landslide',
  '泥石流': 'mudslide',
  '道路损坏': 'road_damage',
  '交通事故': 'traffic_accident',
  '其他': 'other'
};

// 获取标记图标
function getMarkerIcon() {
  // 根据灾害类型和状态返回不同的图标
  const typeClass = disasterTypeMap[disaster.value.disasterType] || 'other';
  
  // 这里可以根据不同类型返回不同的图标URL
  const iconMap = {
    flood: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
    fire: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
    earthquake: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-yellow.png',
    landslide: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-orange.png',
    other: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png'
  };
  
  return iconMap[typeClass] || iconMap.other;
}

// 获取灾害标签内容
function getDisasterLabel() {
  return `${disaster.value.disasterType} (${getStatusText(disaster.value.status)})`;
}

// 获取详细地址信息
async function fetchDetailedLocation() {
  try {
    if (!disaster.value.longitude || !disaster.value.latitude) {
      locationText.value = '无法获取位置信息：经纬度数据缺失';
      return;
    }
    
    // 使用高德地图API进行逆地理编码
    const result = await MapUtils.getAddressByLocation(
      disaster.value.longitude,
      disaster.value.latitude
    );
    
    if (result && result.formattedAddress) {
      locationText.value = result.formattedAddress;
    } else {
      locationText.value = '无法解析位置信息';
    }
  } catch (error) {
    console.error('获取地址信息失败:', error);
    locationText.value = '获取地址信息失败';
  }
}

// 复制图片URL到剪贴板
function copyImageUrl() {
  if (disaster.value.video_url) {
    navigator.clipboard.writeText(disaster.value.video_url)
      .then(() => {
        message.success('图片URL已复制到剪贴板');
      })
      .catch(err => {
        console.error('复制失败:', err);
        message.error('复制失败');
      });
  }
}

onMounted(async () => {
  const disasterId = route.params.id;
  
  if (!disasterId) {
    message.error('未指定灾害ID');
    router.push({ name: 'disaster_list' });
    return;
  }
  
  loading.value = true;
  
  try {
    // 获取灾害详情
    const data = await RoadDisasterApi.getRoadDisasterById(disasterId);
    
    // 解析返回的数据
    let parsedData;
    if (typeof data === 'string') {
      try {
        parsedData = JSON.parse(data);
      } catch (e) {
        console.error('解析灾害详情失败:', e);
        message.error('解析灾害详情失败');
        return;
      }
    } else {
      parsedData = data;
    }
    
    // 更新灾害数据
    disaster.value = parsedData;
    
    // 获取详细地址
    fetchDetailedLocation();
  } catch (error) {
    console.error('获取灾害详情失败:', error);
    message.error('获取灾害详情失败: ' + (error.message || '未知错误'));
    
    // 使用模拟数据
    disaster.value = {
      disasterID: Number(disasterId),
      disasterType: '洪水',
      disasterInfo: '这是一个模拟的灾害信息，由于无法获取真实数据而显示。',
      longitude: 116.404,
      latitude: 39.915,
      userID: 1001,
      status: 'unverified',
      video_url: 'https://img.freepik.com/free-photo/city-floods-concept_23-2149888762.jpg',
    };
    fetchDetailedLocation();
  } finally {
    loading.value = false;
  }
});

// 获取状态文本
function getStatusText(status) {
  return statusMap[status] || status;
}

// 获取状态标签类型
function getStatusType(status) {
  return statusTypeMap[status] || 'default';
}

// 验证灾害
async function handleVerify() {
  try {
    await RoadDisasterApi.updateDisasterStatus(disaster.value.disasterID, 'verified');
    message.success('灾害已验证');
    disaster.value.status = 'verified';
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}

// 标记灾害已解决
async function handleResolve() {
  try {
    await RoadDisasterApi.updateDisasterStatus(disaster.value.disasterID, 'resolved');
    message.success('灾害已标记为解决');
    disaster.value.status = 'resolved';
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}
</script>

<style lang="less" scoped>
.disaster-content {
  margin: 16px 0;
  
  .content-box {
    padding: 16px;
    background-color: #f9f9f9;
    border-radius: 4px;
    min-height: 100px;
    white-space: pre-wrap;
  }
}

.disaster-map {
  margin: 16px 0;
  
  .map-container {
    width: 100%;
    height: 400px;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .amap-box {
      width: 100%;
      height: 100%;
    }
  }
}

.disaster-image {
  margin: 16px 0;
  
  .image-card {
    display: flex;
    justify-content: center;
  }
  
  .image-container {
    display: flex;
    justify-content: center;
    padding: 10px;
  }
  
  .disaster-image-preview {
    max-width: 100%;
    max-height: 500px;
    object-fit: contain;
    border-radius: 4px;
  }
}

.action-buttons {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style>
